#!/bin/sh
# This regression test is a part of SIPp.
# A message SIPp sends by itself that fails to go out (here the CANCEL
# of a call aborted after its connection closed) is a warning, and the
# call is still there to finish aborting; -sendbuffer_warn makes it an
# error.
. "`dirname "$0"`/../functions"; init

command -v perl >/dev/null || skip "no perl"

# A server that rings, then closes the connection. SIPp starts once it
# listens: a SIPp that cannot connect fails its call, and exits with 1.
peer() {
    ready=`mktemp`
    perl -e '
        use IO::Socket::INET;
        my $l = IO::Socket::INET->new(LocalAddr => "127.0.0.1:5070",
            Listen => 5, ReuseAddr => 1) or die;
        open(my $r, ">", $ARGV[0]) or die; print $r "ready"; close($r);
        alarm 20;
        while (my $c = $l->accept()) {
            my $m = "";
            while ($m !~ /\r\n\r\n/) { sysread($c, $m, 65536, length $m) or last; }
            my %h;
            for (qw(Via From To Call-ID CSeq)) { $h{$_} = $1 if $m =~ /^$_:\s*(.*?)\r$/mi; }
            syswrite($c, "SIP/2.0 180 Ringing\r\nVia: $h{Via}\r\nFrom: $h{From}\r\n" .
                "To: $h{To};tag=1\r\nCall-ID: $h{\"Call-ID\"}\r\nCSeq: $h{CSeq}\r\n" .
                "Content-Length: 0\r\n\r\n");
            select(undef, undef, undef, 0.2);
            close($c);
        }' "$ready" &
    i=0
    while ! test -s "$ready" && kill -0 $! 2>/dev/null && test $i -lt 100; do
        i=$((i+1))
        sleep 0.1
    done
    test -s "$ready"; started=$?
    rm -f "$ready"
    test $started -eq 0 || fail "the peer did not start"
}

# Unfixed, the freed call made SIPp spin.
uac() {
    timeout -sKILL 20 "`get_sipp`" -nostdin "$@" >/dev/null 2>&1
}
opts="-sn uac -t tn -i 127.0.0.1 -p 5071 -m 1 -max_reconnect 3
    -reconnect_close false -reconnect_sleep 100 -recv_timeout 2000"

peer
uac $opts 127.0.0.1:5070
status=$?
pkill -P$$; wait
test $status -eq 1 || fail "the aborted call exited with $status, not 1"

peer
uac $opts -sendbuffer_warn true 127.0.0.1:5070
status=$?
test $status -eq 255 || fail "-sendbuffer_warn exited with $status, not 255"
ok
